<?php
namespace Emos\Field;

class ItemSet extends AbstractItem {
    var $elements = array();    
    
    public function add($name, $label, $field) {
        static $count = 0;
        
        if($name === null) {
            $count++;
            $name = '__field_'.$count;
        }
        
        $field->name = $name;
        $field->label = $label;
        
        $this->elements[$name] = $field;
        if(!($field instanceof ItemSet)) {
            $this->fields[$name] = $field;
        }
        
        return $field;
    }
    
    public function getTemplate() {
        ob_start();
        
        foreach($this->elements as $name=>$element) {
            $label = $element->label;  
            
            $nuller = '';
            
            if($element instanceof ItemSet) {            
                $control = $element->getTemplate();
            }
            else {                
                $control = '{'.$name.'}';
            }            
            
            if($label === null) {                
                print "<div class='item withoutLabel' data-field='{$name}'>";                
                print "  <div class='control'>{$control}</div>";
                print "  <div class='clear'></div>";                
                print "</div>";
            }
            else {
                print "<div class='item withLabel' data-field='{$name}'>";                
                print "  <label>".$label."</label>";
                print "  <div class='control'>{$control}</div>";
                print "  <div class='clear'></div>";
                print "</div>";
            }
            
        }        
        
        return ob_get_clean();
    }
    
    public function getControls() {
        $fields = array();
        foreach($this->elements as $name=>$element) {
            if($element instanceof ItemSet) {
                $fields += $element->getControls();            
            }
            else {
                $fields[$name] = $element;
            }
        }
        return $fields;
    }
}
